/**
 * Created with IntelliJ IDEA.
 * User: Jeremy Schulte
 * Date: 11/15/13
 * Time: 7:16 PM
 */
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import java.awt.print.PrinterException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class PracticeControl {

    // DB.
    private Connection dbConnect;
    private Statement statement;
    private String createStmt;
    private String insertStmt;
    private String selectStmt;

    // For debug purposes.
    private static boolean DEBUG = false;

    // For setting Others text.
    static String setForms;
    static String setSteps;
    static String setKnowledge;
    static String setOther;
    static File prefsFile;
    static String readOther;




    // Allows for database creation.
    public void dbCreate() {
        try {
            dbConnect = DriverManager
                    .getConnection("jdbc:derby:practiceDB; create = true");
            if (DEBUG)
                System.out.println("Connected for creation.");
            statement = dbConnect.createStatement();
            createStmt = "CREATE TABLE practice" + "(Date CHAR(9) ,"
                    + "Forms CHAR(11) ," + "Steps CHAR(11) ,"
                    + "Knowledge CHAR(11)," + "Other CHAR(11))";
            statement.execute(createStmt);
            statement.close();
            dbConnect.close();
            JOptionPane.showMessageDialog(null, "Database created.", "Success",
                    JOptionPane.INFORMATION_MESSAGE);
            PracticeGUI.statusLabel.setText("Database Created.");
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null,
                    "Database error.  It may already exist.\n", "Error",
                    JOptionPane.ERROR_MESSAGE);
            PracticeGUI.statusLabel.setText("Database Creation Error.");
            if (DEBUG)
                e.printStackTrace();

        }

    }

    // Coded by Jeremy Schulte. This methods writes to the database.)
    public void dbWrite() {
        try {
            dbConnect = DriverManager.getConnection("jdbc:derby:practiceDB");
            if (DEBUG)
                System.out.println("Connected for writing.");
            statement = dbConnect.createStatement();

            try {

                insertStmt = "INSERT INTO practice"
                        + "(Date, Forms, Steps, Knowledge, Other)"
                        + " VALUES ('" + PracticeGUI.returnDate + "',  '"
                        + PracticeGUI.formsTime.getText() + "', '"
                        + PracticeGUI.stepsTime.getText() + "', '"
                        + PracticeGUI.knowledgeTime.getText() + "', '"
                        + PracticeGUI.otherTime.getText() + "')";
                statement.execute(insertStmt);
                PracticeGUI.statusLabel.setText("Saved.");
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null,
                        "Invalid donation. Only use numbers or decimals.",
                        "Error in entry.", JOptionPane.ERROR_MESSAGE);
                PracticeGUI.statusLabel.setText("Error.");

            }

        } catch (SQLException e) {
            if (DEBUG)
                e.printStackTrace();
        }

    }

    // This method reads data from database to store in
    // Table.
    public void dbRead() {
        try {
            dbConnect = DriverManager.getConnection("jdbc:derby:practiceDB");
            if (DEBUG)
                System.out.println("Connected for reading.");
            statement = dbConnect.createStatement();
            selectStmt = "SELECT * FROM practice";
            ResultSet results = statement.executeQuery(selectStmt);
            while (results.next()) {

                // Write data to the JTable.
                PracticeGUI.tableModel.addRow(new Object[] {
                        results.getString("Date"),
                        results.getString("Forms"),
                        results.getString("Steps"),
                        results.getString("Knowledge"),
                        results.getString("Other") });
            }


        } catch (SQLException e) {

            if (DEBUG)
                e.printStackTrace();
        }

    }

    public void dbPrint() {
        try {
            PracticeGUI.resultsTable.print();
        } catch (PrinterException e) {
            if(DEBUG)
                e.printStackTrace();
        }




    }







    public void prefsWrite() throws IOException {
        prefsFile = new File(".prefs");
        FileWriter prefsWrite = new FileWriter(prefsFile, true);
        String[] prefsArray = { "[Forms]", "Forms", "[Steps]", "One-Steps",
                "[Knowledge]", "Knowledge", "[Other]", "Other" };
        for (int i = 0; i < 8; i++) {
            System.out.println(prefsArray[i]);
            prefsWrite.write(prefsArray[i] + "\n");

        }
        prefsWrite.close(); //close the file to write contents.
    }


    //Reads the prefs file into the variables.
    public void prefsRead() throws IOException {
        prefsFile = new File(".prefs");
        Scanner prefsReader = new Scanner(prefsFile);
        if (prefsReader.hasNext()) {
            prefsReader.nextLine();
            setForms = prefsReader.nextLine();
            prefsReader.nextLine();
            setSteps = prefsReader.nextLine();
            prefsReader.nextLine();
            setKnowledge = prefsReader.nextLine();
            prefsReader.nextLine();
            setOther = prefsReader.nextLine();
            prefsReader.close(); //Close reader stream.

        }

    }

    //This method is for executing and launching the
    // application.
    public static void main(String[] args) {
        PracticeGUI pGUI;
        PracticeControl pControl = new PracticeControl();

        // Read prefs.
        try {
            pControl.prefsRead();
        } catch (IOException e) {
            if (DEBUG)
                System.out.println("File not found.");
            // Write default prefs if there is no file found.
            try {
                pControl.prefsWrite();
                pControl.prefsRead();
            } catch (IOException e1) {
                if (DEBUG)
                    e1.printStackTrace();
            }

        }

        // Nimbus Look and Feel.
        try {
            UIManager
                    .setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (UnsupportedLookAndFeelException e) {
            if (DEBUG)
                JOptionPane.showMessageDialog(null,
                        "Unsupported Look and Feel.", "Unsupported",
                        JOptionPane.INFORMATION_MESSAGE);
        } catch (ClassNotFoundException e) {
        } catch (InstantiationException e) {
        } catch (IllegalAccessException e) {
        }

        pGUI = new PracticeGUI();
        pControl = new PracticeControl();

        // Set close operation.
        pGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Pack components until minimum size is hit.
        pGUI.pack();

        // Center of screen.
        pGUI.setLocationRelativeTo(null);

        // View it.
        pGUI.setVisible(true);

    }

}